package com.wing.product.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.product.dao.WarehouseProductInventoryDao;
import com.wing.product.dao.WarehouseQualityTestingDetailDao;
import com.wing.product.dao.WarehouseStorageOrderDao;
import com.wing.product.dao.WarehouseStorageOrderDetailDao;
import com.wing.product.model.entity.*;
import com.wing.product.model.request.WarehouseFinshedProductStorageOrderForm;
import com.wing.product.model.request.WarehouseStorageOrderForm;
import com.wing.product.model.response.WarehouseProductInventoryVO;
import com.wing.product.model.response.WarehouseStorageOrderDetailVO;
import com.wing.product.model.response.WarehouseStorageOrderVO;
import com.wing.warehouse.dao.WarehouseFactoryAdministrationDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WarehouseStorageOrderServiceImpl extends ServiceImpl<WarehouseStorageOrderDao, WarehouseStorageOrder> implements WarehouseStorageOrderService {

    @Autowired
    WarehouseProductInventoryDao warehouseProductInventoryDao;
    @Autowired
    WarehouseProductInventoryService warehouseProductInventoryService;
    @Autowired
    WarehouseStorageOrderDetailService warehouseStorageOrderDetailService;
    @Autowired
    WarehouseStorageOrderDetailDao warehouseStorageOrderDetailDao;
    @Autowired
    WarehouseSignOrderService warehouseSignOrderService;
    @Autowired
    WarehouseQualityTestingService warehouseQualityTestingService;
    @Autowired
    WarehouseProcessingReportService warehouseProcessingReportService;
    @Autowired
    WarehouseComputerPracticeService warehouseComputerPracticeService;
    @Autowired
    WarehouseProductionOrderService warehouseProductionOrderService;
    @Autowired
    WarehouseProductionSchedulingPlanService warehouseProductionSchedulingPlanService;
    @Autowired
    WarehouseProductionSchedulingPlanDetailService warehouseProductionSchedulingPlanDetailService;

    @Autowired
    WarehouseFactoryAdministrationDao warehouseFactoryAdministrationDao;

    @Autowired
    private WarehouseShipmentOrderService warehouseShipmentOrderService;


    @Autowired
    WarehouseQualityTestingDetailDao warehouseQualityTestingDetailDao;
    @Autowired
    WarehouseQualityTestingDetailService warehouseQualityTestingDetailService;
    public Page<WarehouseStorageOrderVO> pageList4appTwo(Page page, Map<String, Object> params) {
        List<WarehouseStorageOrderVO> list = baseMapper.list4appTwo(page, params);
        page.setRecords(list);
        return page;
    }

    public Page<WarehouseStorageOrderVO> pageList4app(Page page, Map<String, Object> params) {
        List<WarehouseStorageOrderVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    @Transactional
    public JsonResult saveWarehouseStorageRecord(WarehouseStorageOrderForm warehouseStorageOrderForm) {
        JsonResult jsonResult = new JsonResult<>();
        if (ObjectUtil.isNotEmpty(warehouseStorageOrderForm)) {
            WarehouseStorageOrder warehouseStorageOrder = new WarehouseStorageOrder();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(WarehouseStorageOrder.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(warehouseStorageOrderForm, warehouseStorageOrder, copyOptions);
            warehouseStorageOrder.setStorageRecordCode(UniqueIdGeneratorUtil.generateUniqueId("RK", "yyyyMMddHHmmss", 1000, 9999));
//            this.baseMapper.insert(warehouseStorageOrder);
            this.save(warehouseStorageOrder);

            List<WarehouseStorageOrderDetail> warehouseStorageOrderDetailList = new ArrayList<>();
            List<WarehouseProductInventory> warehouseProductInventories = new ArrayList<>();
            List<Long> inventoryids = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(warehouseStorageOrderForm.getWarehouseProductInventoryVoList())){
                for (WarehouseProductInventoryVO pi : warehouseStorageOrderForm.getWarehouseProductInventoryVoList()){
                    //收集入库明细数据
                    WarehouseStorageOrderDetail warehouseStorageOrderDetail = new WarehouseStorageOrderDetail();
                    warehouseStorageOrderDetail.setWarehouseStorageOrderId(warehouseStorageOrder.getId());
                    warehouseStorageOrderDetail.setProductUnitId(pi.getUnitId());
                    warehouseStorageOrderDetail.setNetWeight(pi.getNetWeight());
                    warehouseStorageOrderDetail.setGrossWeight(pi.getGrossWeight());
                    warehouseStorageOrderDetail.setUserBundleCode(pi.getUserBundleCode());
                    warehouseStorageOrderDetail.setSysBundleCode(pi.getSysBundleCode());
                    warehouseStorageOrderDetailList.add(warehouseStorageOrderDetail);

                    //产品明细
                    WarehouseProductInventory warehouseProductInventory = new WarehouseProductInventory();
                    warehouseProductInventory.setId(pi.getId());
                    warehouseProductInventory.setFirstEntryDate(LocalDateTime.now());
                    warehouseProductInventory.setWarehouseId(warehouseStorageOrderForm.getWarehouseFactoryAdministrationId());
                    warehouseProductInventory.setWarehouseAreaId(warehouseStorageOrderForm.getWarehouseAreaId());
                    warehouseProductInventory.setWarehouseShelfSpaceId(warehouseStorageOrderForm.getWarehouseFactoryShelfSpaceId());
                    warehouseProductInventory.setProductStatus(3);
                    warehouseProductInventory.setWarehouseStorageOrderId(warehouseStorageOrder.getId());
                    warehouseProductInventory.setInventoryTypeId(warehouseStorageOrderForm.getInventoryTypeId());
                    if (pi.getQuantity() == null){
                        warehouseProductInventory.setQuantity(1);
                    }
                    warehouseProductInventories.add(warehouseProductInventory);
                    inventoryids.add(pi.getId());

                }
                warehouseStorageOrderDetailService.saveBatch(warehouseStorageOrderDetailList);
                warehouseProductInventoryService.updateBatchById(warehouseProductInventories);

                //修改签收状态
                LambdaQueryWrapper<WarehouseProductInventory> inventoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
                inventoryLambdaQueryWrapper.eq(WarehouseProductInventory::getWarehouseSignOrderId,warehouseStorageOrderForm.getSignInRecordId())
                        .eq(WarehouseProductInventory::getIsDeleted,0)
                        .notIn(WarehouseProductInventory::getId,inventoryids);
                List<WarehouseProductInventory> warehouseProductInventorieList = warehouseProductInventoryDao.selectList(inventoryLambdaQueryWrapper);

                Boolean b = true;
                for (WarehouseProductInventory pi : warehouseProductInventorieList){
                    if (ObjectUtil.isEmpty(pi.getWarehouseStorageOrderId()) || pi.getWarehouseStorageOrderId() == 0){
                        b = false;
                    }
                }
                if (b){
                    LambdaUpdateWrapper<WarehouseSignOrder> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    lambdaUpdateWrapper.eq(WarehouseSignOrder::getId,warehouseStorageOrderForm.getSignInRecordId())
                            .set(WarehouseSignOrder::getStatus,3);
                    warehouseSignOrderService.update(lambdaUpdateWrapper);
                }
            }else {
                return jsonResult.fail("添加失败，请选择唯一码");
            }
            return jsonResult.success("添加成功");
        } else {
            return jsonResult.fail("添加失败");
        }
    }

    @Override
    public  WarehouseStorageOrderVO selectStorageRecordDetail(String id){
       WarehouseStorageOrderVO warehouseStorageOrderVO = this.baseMapper.selectStorageRecord(id);

//        LambdaQueryWrapper<WarehouseStorageOrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(WarehouseStorageOrderDetail::getWarehouseStorageOrderId,warehouseStorageOrderVO.id)
//                .eq(WarehouseStorageOrderDetail::getIsDeleted,0);
//        List<WarehouseStorageOrderDetail> warehouseStorageOrderDetailList = warehouseStorageOrderDetailDao.selectList(lambdaQueryWrapper);

        List<WarehouseStorageOrderDetailVO> warehouseStorageOrderDetailList = warehouseStorageOrderDetailDao.list4app(id);

        warehouseStorageOrderVO.setWarehouseStorageOrderDetailList(warehouseStorageOrderDetailList);

        return warehouseStorageOrderVO;

    }

    @Override
    public WarehouseStorageOrderVO findFactoryByUserBundleCode(String userBundleCode) {
        return baseMapper.findFactoryByUserBundleCode(userBundleCode);
    }

    @Override
    public List<WarehouseStorageOrderVO> findSign() {
        return baseMapper.findSign();
    }

    @Override
    @Transactional
    public JsonResult save(WarehouseStorageOrderForm warehouseStorageOrderForm) {
        JsonResult jsonResult = new JsonResult<>();
        if (ObjectUtil.isNotEmpty(warehouseStorageOrderForm)) {
            WarehouseStorageOrder warehouseStorageOrder = new WarehouseStorageOrder();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(WarehouseStorageOrder.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(warehouseStorageOrderForm, warehouseStorageOrder, copyOptions);
            warehouseStorageOrder.setStorageRecordCode(UniqueIdGeneratorUtil.generateUniqueId("RK", "yyyyMMddHHmmss", 1000, 9999));
            warehouseStorageOrder.setWarehouseOrderId(warehouseStorageOrderForm.getWarehouseOrderId());
            warehouseStorageOrder.setWarehouseFactoryShelfSpaceId(warehouseStorageOrderForm.getWarehouseShelfSpaceId());
            baseMapper.insert(warehouseStorageOrder);

            List<WarehouseProductInventory> warehouseProductInventoryList = new ArrayList<WarehouseProductInventory>();
            for (WarehouseProductInventoryVO warehouseProductInventoryVO: warehouseStorageOrderForm.getWarehouseProductInventoryVoList()){
                WarehouseProductInventory warehouseProductInventory=warehouseProductInventoryDao.findByInventoryId(warehouseStorageOrderForm.getInventoryId());
                warehouseProductInventory.setWarehouseTypeId(warehouseProductInventoryVO.getWarehouseTypeId());
//                warehouseProductInventory.setWarehouseId(warehouseProductInventoryVO.getWarehouseId());
                warehouseProductInventory.setWarehouseId(warehouseProductInventoryVO.getWarehouseFactoryAdministrationId());
                warehouseProductInventory.setWarehouseAreaId(warehouseProductInventoryVO.getWarehouseAreaId());
                warehouseProductInventory.setWarehouseShelfSpaceId(warehouseProductInventoryVO.getWarehouseShelfSpaceId());
                warehouseProductInventory.setWarehouseStorageOrderId(warehouseStorageOrder.getId());
                warehouseProductInventory.setInventoryTypeId(warehouseProductInventoryVO.getInventoryTypeId());
                warehouseProductInventory.setWarehouseShelfId(warehouseProductInventoryVO.getWarehouseShelfId());
                warehouseProductInventory.setProductStatus(3);
                warehouseProductInventory.setIsSign(0);
                warehouseProductInventoryList.add(warehouseProductInventory);
                warehouseShipmentOrderService.updateStatus(warehouseProductInventory.getWarehouseShipmentOrderId(),3);
                warehouseSignOrderService.updateStatus(warehouseProductInventory.getWarehouseSignOrderId(),3);
            }
            warehouseProductInventoryService.updateBatchById(warehouseProductInventoryList);
//            warehouseProductInventoryService.updateById(warehouseProductInventory);
            return jsonResult.success("添加成功");
        } else {
            return jsonResult.fail("添加失败");
        }
    }

    @Override
    @Transactional
    public JsonResult saveWarehouseFinshedProductStorageRecord(WarehouseFinshedProductStorageOrderForm warehouseFinshedProductStorageOrderForm){
        JsonResult jsonResult = new JsonResult<>();
        if (ObjectUtil.isNotEmpty(warehouseFinshedProductStorageOrderForm)) {
            WarehouseStorageOrder warehouseStorageOrder = new WarehouseStorageOrder();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(WarehouseStorageOrder.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(warehouseFinshedProductStorageOrderForm, warehouseStorageOrder, copyOptions);
            warehouseStorageOrder.setStorageRecordCode(UniqueIdGeneratorUtil.generateUniqueId("RK", "yyyyMMddHHmmss", 1000, 9999));

            //查询质检记录
            LambdaQueryWrapper<WarehouseQualityTesting> qualityTestingLambdaQueryWrapper = new LambdaQueryWrapper<>();
            qualityTestingLambdaQueryWrapper.eq(WarehouseQualityTesting::getId,warehouseFinshedProductStorageOrderForm.getQualityTestingId());
            WarehouseQualityTesting warehouseQualityTesting = warehouseQualityTestingService.getOne(qualityTestingLambdaQueryWrapper);

            //查询报工记录
            LambdaQueryWrapper<WarehouseProcessingReport> lambdaQueryWrapperProcessingReport = new LambdaQueryWrapper<>();
            lambdaQueryWrapperProcessingReport.eq(WarehouseProcessingReport::getId,warehouseQualityTesting.getProcessingReportId());
            WarehouseProcessingReport warehouseProcessingReport = warehouseProcessingReportService.getOne(lambdaQueryWrapperProcessingReport);

            //查询上机记录
            LambdaQueryWrapper<WarehouseComputerPractice> lambdaQueryWrapperComputerPractice = new LambdaQueryWrapper<>();
            lambdaQueryWrapperComputerPractice.eq(WarehouseComputerPractice::getId,warehouseProcessingReport.getComputerPracticeId());
            WarehouseComputerPractice warehouseComputerPractice = warehouseComputerPracticeService.getOne(lambdaQueryWrapperComputerPractice);

            warehouseStorageOrder.setProductionPlanCode(warehouseComputerPractice.getProductionPlanCode());
            warehouseStorageOrder.setProductionPlanDetailCode(warehouseComputerPractice.getProductionSchedulingPlanDetailCode());
            this.baseMapper.insert(warehouseStorageOrder);

            //查询生产订单
            LambdaQueryWrapper<WarehouseProductionOrder> lambdaQueryWrapperProductionOrder = new LambdaQueryWrapper<>();
            lambdaQueryWrapperProductionOrder.eq(WarehouseProductionOrder::getId,warehouseQualityTesting.getProductionOrderId());
            WarehouseProductionOrder warehouseProductionOrder = warehouseProductionOrderService.getOne(lambdaQueryWrapperProductionOrder);

            //查询生产排产计划明细
            LambdaQueryWrapper<WarehouseProductionSchedulingPlanDetail> lambdaQueryWrapperProductionSchedulingPlanDetail = new LambdaQueryWrapper<>();
            lambdaQueryWrapperProductionSchedulingPlanDetail.eq(WarehouseProductionSchedulingPlanDetail::getId,warehouseComputerPractice.getProductionSchedulingPlanDetailId());
            WarehouseProductionSchedulingPlanDetail warehouseProductionSchedulingPlanDetail = warehouseProductionSchedulingPlanDetailService.getOne(lambdaQueryWrapperProductionSchedulingPlanDetail);

            //查询生产排产计划
            LambdaQueryWrapper<WarehouseProductionSchedulingPlan> lambdaQueryWrapperProductionSchedulingPlan = new LambdaQueryWrapper<>();
            lambdaQueryWrapperProductionSchedulingPlan.eq(WarehouseProductionSchedulingPlan::getId,warehouseProductionSchedulingPlanDetail.getWarehouseProductionSchedulingPlanId());
            WarehouseProductionSchedulingPlan warehouseProductionSchedulingPlan = warehouseProductionSchedulingPlanService.getOne(lambdaQueryWrapperProductionSchedulingPlan);

            List<WarehouseStorageOrderDetail> warehouseStorageOrderDetailList = new ArrayList<>();
            List<WarehouseProductInventory> warehouseProductInventories = new ArrayList<>();
            List<String> userBundleCodes = new ArrayList<>();

            if (CollectionUtils.isNotEmpty(warehouseFinshedProductStorageOrderForm.getWarehouseProductInventoryVoList())){
                for (WarehouseProductInventoryVO pi : warehouseFinshedProductStorageOrderForm.getWarehouseProductInventoryVoList()){
                    //收集入库明细数据
                    WarehouseStorageOrderDetail warehouseStorageOrderDetail = new WarehouseStorageOrderDetail();
                    warehouseStorageOrderDetail.setWarehouseStorageOrderId(warehouseStorageOrder.getId());
                    warehouseStorageOrderDetail.setProductUnitId(pi.getUnitId());
                    warehouseStorageOrderDetail.setNetWeight(pi.getNetWeight());
                    warehouseStorageOrderDetail.setGrossWeight(pi.getGrossWeight());
                    warehouseStorageOrderDetail.setUserBundleCode(pi.getUserBundleCode());
                    warehouseStorageOrderDetail.setSysBundleCode(pi.getSysBundleCode());
                    warehouseStorageOrderDetailList.add(warehouseStorageOrderDetail);

                    userBundleCodes.add(pi.getUserBundleCode());

                    //产品明细
                    WarehouseProductInventory warehouseProductInventory = new WarehouseProductInventory();
//                    CopyOptions copyOptionInventory = CopyOptions.create()
//                            .setEditable(WarehouseProductInventory.class)
//                            .setIgnoreError(true)
//                            .setIgnoreNullValue(true);
//                    BeanUtil.copyProperties(pi, warehouseProductInventory, copyOptionInventory);
                    warehouseProductInventory.setId(pi.getId());
                    warehouseProductInventory.setFirstEntryDate(LocalDateTime.now());
                    warehouseProductInventory.setWarehouseId(warehouseFinshedProductStorageOrderForm.getWarehouseFactoryAdministrationId());
//                    warehouseProductInventory.setWarehouseAreaId(warehouseFinshedProductStorageOrderForm.getWarehouseAreaId());
//                    warehouseProductInventory.setWarehouseShelfSpaceId(warehouseFinshedProductStorageOrderForm.getWarehouseFactoryShelfSpaceId());
                    warehouseProductInventory.setWarehouseAreaId(pi.getWarehouseAreaId());
                    warehouseProductInventory.setWarehouseShelfSpaceId(pi.getWarehouseShelfSpaceId());
                    warehouseProductInventory.setProductStatus(3);
                    warehouseProductInventory.setInventoryTypeId(warehouseFinshedProductStorageOrderForm.getInventoryTypeId());
                    warehouseProductInventory.setFirstEntryDate(warehouseStorageOrder.getCreateTime());
                    if (pi.getQuantity() == null){
                        warehouseProductInventory.setQuantity(1);
                    }
                    warehouseProductInventories.add(warehouseProductInventory);
                }
                warehouseStorageOrderDetailService.saveBatch(warehouseStorageOrderDetailList);
                warehouseProductInventoryService.updateBatchById(warehouseProductInventories);

                //修改质检状态
//                LambdaUpdateWrapper<WarehouseQualityTestingDetail> qualityTestingDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
//                qualityTestingDetailLambdaUpdateWrapper.eq(WarehouseQualityTestingDetail::getIsDeleted,0)
//                                .in(WarehouseQualityTestingDetail::getFinishedProductBundleCode,userBundleCodes)
//                        .set(WarehouseQualityTestingDetail::getStatus,2);
                warehouseQualityTestingDetailService.lambdaUpdate().eq(WarehouseQualityTestingDetail::getIsDeleted,0)
                        .in(WarehouseQualityTestingDetail::getFinishedProductBundleCode,userBundleCodes)
                        .set(WarehouseQualityTestingDetail::getStatus,2).update();

                LambdaQueryWrapper<WarehouseQualityTestingDetail> qualityTestingDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
                qualityTestingDetailLambdaQueryWrapper.eq(WarehouseQualityTestingDetail::getIsDeleted,0)
                        .eq(WarehouseQualityTestingDetail::getQualityTestingId,warehouseFinshedProductStorageOrderForm.getQualityTestingId());
                List<WarehouseQualityTestingDetail> warehouseQualityTestingDetails = warehouseQualityTestingDetailDao.selectList(qualityTestingDetailLambdaQueryWrapper);

                Boolean b = true;
                for (WarehouseQualityTestingDetail wqtd : warehouseQualityTestingDetails){
                    if (wqtd.getStatus().equals(1)){
                        b = false;
                    }
                }
                if (b){
                    warehouseQualityTesting.setStatus(2);
                    warehouseQualityTestingService.updateById(warehouseQualityTesting);
                }



                //修改生产订单
                if (warehouseProductionOrder.getFinishedProductNumber() != null){
                    warehouseProductionOrder.setFinishedProductNumber(warehouseProductionOrder.getFinishedProductNumber()+warehouseFinshedProductStorageOrderForm.getInventoryQuantity());
                }else {
                    warehouseProductionOrder.setFinishedProductNumber(warehouseFinshedProductStorageOrderForm.getInventoryQuantity());
                }
                warehouseProductionOrderService.updateById(warehouseProductionOrder);

                //修改生产排产计划
                if (warehouseProductionSchedulingPlan.getFinishedProductNumber()!= null){
                    warehouseProductionSchedulingPlan.setFinishedProductNumber(warehouseProductionSchedulingPlan.getFinishedProductNumber()+warehouseFinshedProductStorageOrderForm.getInventoryQuantity());
                }else {
                    warehouseProductionSchedulingPlan.setFinishedProductNumber(warehouseFinshedProductStorageOrderForm.getInventoryQuantity());
                }
                warehouseProductionSchedulingPlanService.updateById(warehouseProductionSchedulingPlan);

                //修改生产排产计划明细
                if (warehouseProductionSchedulingPlanDetail.getFinishedProductNumber()!= null){
                    warehouseProductionSchedulingPlanDetail.setFinishedProductNumber(warehouseProductionSchedulingPlanDetail.getFinishedProductNumber()+warehouseFinshedProductStorageOrderForm.getInventoryQuantity());
                }else {
                    warehouseProductionSchedulingPlanDetail.setFinishedProductNumber(warehouseFinshedProductStorageOrderForm.getInventoryQuantity());
                }
                warehouseProductionSchedulingPlanDetailService.updateById(warehouseProductionSchedulingPlanDetail);
            }
            return jsonResult.success("添加成功");
        } else {
            return jsonResult.fail("添加失败");
        }
    }

    @Override
    public WarehouseStorageOrderVO info(String id) {
        WarehouseStorageOrderVO warehouseStorageOrderVO=baseMapper.info(id);
        warehouseStorageOrderVO.setWarehouseFactoryShelfSpaceVOList(warehouseFactoryAdministrationDao.info(Long.parseLong(warehouseStorageOrderVO.getInventoryId())));
        return warehouseStorageOrderVO;
    }
}
